<!-- 
 +----------------------------------------------------------------------
 | 狂团[kt8.cn]旗下KtAdmin是为独立版SAAS系统而生的快速开发框架.
 +----------------------------------------------------------------------
 | [KtAdmin] Copyright (c) 2022 http://ktadmin.cn All rights reserved.
 +----------------------------------------------------------------------
 | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
 +---------------------------------------------------------------------- 
-->
<script setup>
import { Download } from '@element-plus/icons-vue'
import { reactive, ref, onMounted, getCurrentInstance } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { packagelist, cardList, cardDele, cardAdd, cardDetailList, cardAuth, cardAgentList, packageinfo,getCodeList } from '@/api';

const ruleFormLabelWidth = ref('80px')
const router = useRouter()
const dialogFormVisible = ref(false)
const ruleFormRef = ref()
const multipleSelection = ref([])
const formdata = reactive({
	page: 1,
	size: 10,
	remark: ''
})
const packageDataList = ref([])
const getPackageList = async()=>{
	const r = await packagelist({
		size:9999
	})
	if(r){
	packageDataList.value = r.data
	}
}
getPackageList()
const isUnuse = ref(false)
const exportExcel = async () => {
	console.log(tempObj, 'sdfsdfsdf')
	// const r = await postCardExcel({
	//     id:tempObj.value.id,
	//     status:isUnuse.value?0:''
	// })
	// if(r){

	// }
	let url =
		window.location.origin +
		'/base/admin/card/downexcel?id=' +
		tempObj.value.id +
		'&status=' +
		(isUnuse.value ? 0 : '')
	window.open(url)
	console.log(url)
}
const tempObj = ref({})
const handleSizeChange = (val) => {
	formdata.size = val
	getList()
}
const handleCurrentChange = (val) => {
	formdata.page = val
	getList()
}
const handleSizeChange1 = (val) => {
	query.size = val
	getTempData()
}
const handleCurrentChange1 = (val) => {
	query.page = val
	getTempData()
}
const codeList = ref()
const getDataCode = async()=>{
	const r = await getCodeList()
	if(r){
		codeList.value = r.data
	}
}
getDataCode()
const save = async () => {
	if(ruleForm.package_index!==''){
		ruleForm.package_id = packageDataList.value[ruleForm.package_index].id
	}
	
	const r = await cardAdd(ruleForm)
	if (r) {
		dialogVisible.value = false
		getList()
	}
}
const dele = (id) => {
	ElMessageBox.confirm('确定要删除吗？', '提示', {
		type: 'warning',
		center: true
	}).then(() => {
		cardDele({ id: id }).then((res) => {
			ElMessage({
				message: '删除成功',
				type: 'success'
			})
			getList()
		})
	})
}
const types = [
	// '对话次数','绘画次数','vip时长'
	'套餐',
	// '',
	'应用'
]
const sizes1 = ['条']
const sizes2 = ['日', '', '月', '', '年']
const tableData = [
	{
		id: 1,
		level: '1',
		name: '15538889999'
	}
]
const changeType = () => {
	if (ruleForm.type == 1 && ruleForm.size > 1) {
		ruleForm.size = 1
	}
}
const applist = ref([
	{
		img: 'http://weidogstest.oss-cn-beijing.aliyuncs.com/base/base_6319a895619a8.png',
		name: '主应用dmo'
	},
	{
		img: 'https://kt8logo.oss-cn-beijing.aliyuncs.com/app.png',
		name: '狂团demo插件'
	},
	{
		img: 'http://weidogstest.oss-cn-beijing.aliyuncs.com/svideo/1/svideo_62df5b8419da1.jpg',
		name: '企微魔盒'
	}
])
const handleSelectionChange = (val) => {
	multipleSelection.value = val
}
const appshow = ref(false)
const addapp = () => {
	appshow.value = true
}
// 获取数据,先定一个reactive ，不然赋值的数据不是响应式
let states = reactive({
	tableData: [
		{
			id: 1,
			name: 122
		}
	]
})

let isadmin = ref()
const getList = () => {
	cardList(formdata).then((res) => {
		console.log(res, '3333')
		states.tableData = res.data.item
		states.total = res.data.count
		// isadmin.value = res.data.isadmin
	})
}

onMounted(() => {
	getList()
})
const dialogVisible = ref(false)
const addFun = () => {
	dialogVisible.value = true
	title.value = '生成卡密'
	Object.assign(ruleForm, {
		"type": '1',
  "package_id": '',
  package_index:'',
  "specs_id": '',
  "duration": '',
  "duration_type": '',
  "code": "",
  "amount": '',
  "remark": ""
	})
}
// const editFun = (val) => {
// 	ruleForm.name = val.name
// 	ruleForm.price = val.price
// 	ruleForm.id = val.id
// 	dialogVisible.value = true
// 	appidata.appindex = []
// 	ruleForm.specs = []
// 	ruleForm.name = ''
// 	packageinfo({ id: val.id }).then((res) => {
// 		ruleForm.name = res.data.name
// 		ruleForm.specs = res.data.specs
// 		appidata.appindex = res.data.apps
// 		console.log(appidata.appindex)
// 	})
// 	getMarketlist().then((res) => {
// 		applist.value = res.data
// 	})
// 	title.value = '编辑'
// }
const rules = reactive({
	name: [{ required: true, message: '请输入套餐名称', trigger: 'blur' }],
	price: [{ required: true, message: '请输入套餐价格', trigger: 'blur' }]
})
const deleteFun = (id) => {
	console.log(id)
	deleteTC(id).then((res) => {
		console.log(res)
		getList()
	})
}
const title = ref('新增')
const ruleForm = reactive({
	"type": '1',
  "package_id": '',
  package_index:'',
  "specs_id": '',
  "duration": '',
  "duration_type": '',
  "code": "",
  "amount": '',
  "remark": ""
})
const addlist = () => {
	var data = {
		id: ruleForm.specs.length > 0 ? ruleForm.specs[ruleForm.specs.length - 1].id + 1 : 1,
		duration: '',
		price: '',
		old_price: '',
		duration_type: '3'
	}
	console.log(ruleForm.specs, ruleForm.specs.length)
	ruleForm.specs.push(data)
}
// 删除表格一列
const deletelist = (val, row) => {
	if (ruleForm.specs.length == 1) {
		ElMessage({
			message: '无法删除，最少有一项',
			type: 'warning'
		})
	} else {
		ruleForm.specs.splice(val.index, 1)
	}
}
// 查询数据
const formInline = reactive({
	phoneNumber: '',
	region: '',
	state: ''
})
// 查询提交
const onSubmit = () => {
	console.log('submit!')
	console.log(formInline)
}
// 跳转

const testFun = (isadmin) => {
	console.log(isadmin)
}
const submitForm = async (formEl) => {
	if (title.value == '编辑') {
		if (!formEl) return
		await formEl.validate((valid, fields) => {
			if (valid) {
				console.log(appidata.appindex, ruleForm.specs, ruleForm.name)
				cardAdd({ id: ruleForm.id, name: ruleForm.name, specs: ruleForm.specs, apps: appidata.appindex }).then(
					(res) => {
						ElMessage({ message: '提交成功', type: 'success' })
						dialogVisible.value = false
						getList()
					}
				)
				// updateddTC({ name: ruleForm.name, price: ruleForm.price, id: ruleForm.id }).then((res) => {
				// 	ElMessage({ message: '提交成功', type: 'success' })
				// 	dialogVisible.value = false
				// 	getList()
				// })
			} else {
				console.log('error submit!', fields)
				ElMessage({ message: '失败', type: 'info' })
			}
		})
	} else {
		if (!formEl) return
		await formEl.validate((valid, fields) => {
			if (valid) {
				cardAdd({ name: ruleForm.name, specs: ruleForm.specs, apps: appidata.appindex }).then((res) => {
					ElMessage({ message: '提交成功', type: 'success' })
					dialogVisible.value = false
					getList()
				})
			} else {
				console.log('error submit!', fields)
				ElMessage({ message: '失败', type: 'info' })
			}
		})
	}
}
const appidata = reactive({
	appindex: [],
	appxuan: []
})
const isShowDetail = ref(false)
const query = reactive({
	id: '',
	page: 1,
	size: 20
})
const totalTemp = ref(0)
const tableDataTemp = ref([])
const editFun = async (id, row) => {
	// 查看弹窗

	tempObj.value = row

	query.id = id

	getTempData()
	isShowDetail.value = true

	// router.push({ path: 'add', query: { id: id } })
	// localStorage.setItem('temp',JSON.stringify(row))
}
const getTempData = async () => {
	const r = await cardDetailList(query)
	if (r) {
		totalTemp.value = r.data.count
		tableDataTemp.value = r.data.item
	}
}
const handleClose1 = () => {
	isShowDetail.value = false
}
const checkapp = (val, index) => {
	console.log(appidata.appindex, appidata.appxuan, appidata.appindex.indexOf(val.code))
	if (appidata.appindex.indexOf(val.code) != -1) {
		// appidata.appindex.splice(index, 1)
		// appidata.appxuan.splice(index, 1)
		for (var i = 0; i < appidata.appindex.length; i++) {
			if (val.code == appidata.appindex[i]) {
				appidata.appindex.splice(i, 1)
				appidata.appxuan.splice(i, 1)
				console.log(appidata.appindex)
			}
		}
	} else {
		appidata.appindex.push(val.code)
		appidata.appxuan.push(val)
		console.log(appidata.appindex)
	}
}
const isAuth = ref(false)
const isAdmin = ref(false)
const getAuth = async()=>{
	const r = await cardAuth()
	if(r){
		if(r.data.card_auth){
		isAuth.value = true	
		}
		if(r.data.isadmin){
			isAdmin.value = true
			getAgentList()
		}
	}
	
}
// getAuth()
const agentList = ref()
const getAgentList=async()=>{
	const r = await cardAgentList({
		size:999
	})
	if(r){
		agentList.value = r.data.item
	}
}
</script>

<template>
	<div>
		<div class="public-container">
			<el-row>
				<el-col :span="24" style="margin-bottom: 10px">
					<div style="display: flex; justify-content: space-between">
						<el-button type="primary" @click="addFun">生成卡密</el-button>
						<!-- <el-input
							v-model="formdata.remark"
							style="width: 200px"
							@change="
								formdata.page = 1
								getList()
							"
							placeholder="请输入备注"
						></el-input> -->
					</div>
				</el-col>
			</el-row>
			<el-table
				ref="multipleTableRef"
				:data="states.tableData"
				style="width: 100%"
				:header-cell-style="{ color: '#909399', fontSize: '14px', backgroundColor: '#F7F9FA', padding: '10px 0' }"
				:cell-style="{ fontSize: '14px', padding: '20px 0' }"
				@selection-change="handleSelectionChange"
			>
				<el-table-column property="id" label="批次Id" width="80" />

				<el-table-column property="ctime" label="生成时间" />



				<el-table-column label="面额" width="170">
					<template #default="scope">
						{{ scope.row.duration }}
						{{scope.row.duration_type==1?'天':scope.row.duration_type==2?'月':scope.row.duration_type==3?'年':''}}
						<!-- <div>{{scope.row.month_num}}个月，每月{{ scope.row.month_max_duration }}分钟</div> -->
					</template>
				</el-table-column>
				<el-table-column property="amount" label="卡密数量" />
				<el-table-column property="remark" label="备注" />

				<el-table-column property="use_size" label="已使用" />

				<el-table-column label="操作" width="150">
					<template #default="scope">
						<el-button link type="primary" @click="editFun(scope.row.id, scope.row)"> 查看 </el-button>
						<el-button link type="primary" @click="dele(scope.row.id)">删除 </el-button>
					</template>
				</el-table-column>
			</el-table>
			<div style="margin-top: 7px; float: right">
				<el-pagination
					v-model:currentPage="formdata.page"
					v-model:page-size="formdata.size"
					:page-sizes="[10, 20, 30, 40]"
					:small="small"
					:disabled="disabled"
					:background="background"
					layout="total, sizes, prev, pager, next, jumper"
					:total="states.total"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
				/>

			
			</div>
		</div>
		<!-- 弹窗 -->
		<el-dialog v-model="dialogVisible" :title="title">
			<el-form :model="ruleForm">

				<el-form-item label="类型" :label-width="ruleFormLabelWidth">
					<el-radio-group v-model="ruleForm.type">
						<el-radio label="1">套餐</el-radio>
						<el-radio label="2">应用</el-radio>
					</el-radio-group>
				</el-form-item>

				<template v-if="ruleForm.type==1">
					<el-form-item label="选择套餐" :label-width="ruleFormLabelWidth">
					<el-select @change="ruleForm.specs_id=''" v-model="ruleForm.package_index">
						<el-option :label="item.name" :value="index" v-for="(item,index) in packageDataList">
							
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="选择规格" :label-width="ruleFormLabelWidth">
					<el-select v-model="ruleForm.specs_id">
						<el-option v-if="ruleForm.package_index!==''"  :label="item.duration+(item.duration_type==1?'天':item.duration_type==2?'月':item.duration_type==3?'年':'')" :value="item.id" v-for="(item,index) in packageDataList[ruleForm.package_index].specs">
							
						</el-option>
					</el-select>
				</el-form-item>
				</template>
				<template v-else>
					
					<el-form-item label="周期" :label-width="ruleFormLabelWidth">
					<el-select v-model="ruleForm.duration_type">
						<el-option label="天" :value="1"></el-option>
							<el-option label="月" :value="2"></el-option>
							<el-option label="年" :value="3"></el-option>
					</el-select>
				</el-form-item>
					<el-form-item
					:label="(ruleForm.duration_type==1?'天':ruleForm.duration_type==2?'月':ruleForm.duration_type==3?'年':'')+'时长'"
					:label-width="ruleFormLabelWidth"
				>
					<el-input style="width: 200px" v-model="ruleForm.duration" autocomplete="off">
						<!-- <template #append >分钟</template> -->
					</el-input>
				</el-form-item>
				<el-form-item label="应用code" :label-width="ruleFormLabelWidth">
					<el-select style="width: 200px" v-model="ruleForm.code">
						<el-option v-for="(item,index) in codeList" :label="item.name" :value="item.code">

						</el-option>
					</el-select>
				</el-form-item>
				</template>
				
				

				<el-form-item label="卡密数量" :label-width="ruleFormLabelWidth">
					<el-input style="width: 200px" v-model="ruleForm.amount" autocomplete="off" />
				</el-form-item>

			
				
				

				<el-form-item label="备注" :label-width="ruleFormLabelWidth">
					<el-input type="textarea" v-model="ruleForm.remark" autocomplete="off" />
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="save">保存</el-button>
				</span>
			</template>
		</el-dialog>

		<!-- 详情 -->
		<el-drawer
			ref="drawerRef"
			v-model="isShowDetail"
			:title="'卡密管理，批次ID：' + tempObj.id"
			:before-close="handleClose1"
			direction="rtl"
			size="70%"
			class=""
		>
			<div class="card-drawer">
				<div class="">
					<el-button @click="exportExcel" type="primary" :icon="Download">导出Excel</el-button>
					<el-checkbox class="ml20" v-model="isUnuse" label="只导出未使用" size="large" />
				</div>
				<el-table
					ref="multipleTableRef"
					:data="tableDataTemp"
					style="margin-top: 20px; width: 100%"
					:header-cell-style="{ color: '#909399', fontSize: '14px', backgroundColor: '#F7F9FA', padding: '10px 0' }"
					:cell-style="{ fontSize: '14px', padding: '20px 0' }"
					@selection-change="handleSelectionChange"
				>
					<el-table-column property="id" label="Id" />

					<el-table-column property="code" label="卡密" />

					<el-table-column property="time" label="使用时间" />

					<el-table-column property="user" label="使用成员" />

					<!-- <el-table-column property="size" label="数量" /> -->

					<el-table-column label="类型" width="150">
						<template #default="scope">
							<div v-if="scope.row.type">
								{{ types[scope.row.type - 1] }}
							</div>
						</template>
					</el-table-column>

					<el-table-column label="状态" width="150">
						<template #default="scope">
							{{ scope.row.status == 1 ? '已使用' : '未使用' }}
						</template>
					</el-table-column>

					<!-- <el-table-column label="操作" width="80">
					<template #default="scope">
						<el-button link type="primary" @click="editFun(scope.row.id,scope.row)"> 查看 </el-button>
						<el-button link type="primary" @click="dele(scope.row.id)">删除 </el-button>
					
					</template>
				</el-table-column> -->
				</el-table>
				<div style="margin-top: 7px; float: right">
					<el-pagination
						v-model:currentPage="query.page"
						v-model:page-size="query.size"
						:page-sizes="[10, 20, 30, 40]"
						:small="small"
						:disabled="disabled"
						:background="background"
						layout="total, sizes, prev, pager, next, jumper"
						:total="totalTemp"
						@size-change="handleSizeChange1"
						@current-change="handleCurrentChange1"
					/>
				</div>
			</div>
		</el-drawer>
	</div>
</template>

<style lang="scss" scoped>
.public-container {
	margin: 20px 0px 0 0px !important;
	background: #fff;
	// padding: 20px;
	border-radius: 4px;
}
.card-drawer {
	.ml20 {
		margin-left: 20px;
	}
}
</style>
